#include "xml_util.h"

#include <iostream>
#include <fstream>
#include <string.h>

void xml_util_parse_sax(const char *filename, void *userData, XML_StartElementHandler startTag, XML_EndElementHandler endTag, XML_CharacterDataHandler charData, XML_ProcessingInstructionHandler procInst)
{
	int length;
	int done = 0;
	ifstream is;
	char buff[128];
	XML_Parser parser;

	parser = XML_ParserCreateNS(NULL, '.');
	
	XML_SetUserData(parser, userData);
	XML_SetElementHandler(parser, startTag, endTag);

	if(charData)
		XML_SetCharacterDataHandler(parser, charData);

	if(procInst)
		XML_SetProcessingInstructionHandler(parser, procInst);
	
	is.open (filename, ios::in);

	do
	{
		length = is.readsome(buff, 128);
		XML_Parse(parser, buff, length, done);
	}
	while(length && !done);
	
	is.close();
}

const char* xml_util_getattribute(const char **attrs, const char *name)
{
	while(*attrs)
	{
		const char *n = *(attrs++);
		const char *v = *(attrs++);
		
		if(strcmp(n, name) == 0)
			return v;
	}
	return "";
}

map<string,string> xml_util_getattributesmap(const char **attrs)
{
	map<string,string> attrsMap;
	
	while(*attrs)
	{
		string n(*(attrs++));
		string v(*(attrs++));
		attrsMap[n] = v;
	}
	
	return attrsMap;
}
